package com.ljd.blog.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.ljd.blog.pojo.Blog;
import com.ljd.blog.pojo.User;
import com.ljd.blog.service.BlogService;
import com.ljd.blog.service.TagService;
import com.ljd.blog.service.TypeService;
import com.ljd.blog.vo.BlogQuery;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ljd
 * @version 1.0
 */
@Controller
@RequestMapping("/admin")
public class BlogController {


    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;

    @GetMapping("/blogs")
    public String blogs(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable, BlogQuery blog, Model model) {
        model.addAttribute("types", typeService.listType());
        model.addAttribute("page", blogService.listBlog(pageable, blog));
        return "admin/blogs";
    }

    @PostMapping("/blogs/search")
    public String search(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable, BlogQuery blog, Model model) {
        model.addAttribute("page", blogService.listBlog(pageable, blog));
        //局部渲染
        return "admin/blogs :: blogList";
    }

    private void setTypeAndTag(Model model) {
        model.addAttribute("types", typeService.listType());
        model.addAttribute("tags", tagService.listTag());
    }

    @GetMapping("/blogs/input")
    public String input(Model model) {
        setTypeAndTag(model);
        model.addAttribute("blog", new Blog());
        return "admin/blogs-input";
    }

    @GetMapping("/blogs/{id}/input")
    public String editInput(@PathVariable Long id, Model model) {
        setTypeAndTag(model);
        Blog blog = blogService.getBlog(id);
        blog.init();
        model.addAttribute("blog", blogService.getBlog(id));
        return "admin/blogs-input";
    }

    @PostMapping("/blogs")
    public String post(Blog blog, RedirectAttributes attributes, HttpSession session) {
        blog.setUser((User) session.getAttribute("user"));
        blog.setType(typeService.getType(blog.getType().getId()));
        blog.setTags(tagService.listTag(blog.getTagIds()));
        Blog b;
        if (blog.getId() == null) {
            b = blogService.saveBlog(blog);
        } else {
            b = blogService.updateBlog(blog.getId(), blog);
        }

        if (b == null) {
            attributes.addFlashAttribute("message", "操作失败");
        } else {
            attributes.addFlashAttribute("message", "操作成功");
        }
        return "redirect:/admin/blogs";
    }


    @GetMapping("/blogs/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes) {
        blogService.deleteBlog(id);
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/admin/blogs";
    }

    @PostMapping("/blogs/md/uploadfile")
    @ResponseBody
    public Map uploadfile(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file,
                          HttpServletRequest request,
                          HttpServletResponse response) {
        Map map = new HashMap();
        try {
            //设置
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "text/html");
            //这个地址拿到的是项目根路径所在的地址。
            ApplicationHome h = new ApplicationHome(getClass());
            File jarF = h.getSource();
            //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
            String dirPath = jarF.getParentFile().toString()+"/upload/";
            System.out.println(dirPath);
            String pathRoot1 = Blog.class.getResource("/").getPath().replaceAll("^(/)|(/WEB-INF/classes/)$", "");
            //存放图片的地址（target文件夹下）
            String rootPath =pathRoot1+"static/images/blog/";
//              System.out.println("editormd上传图片："+rootPath);//图片将要上传的位置

            /**
             * 文件路径不存在则需要创建文件路径
             * */
            File filePath = new File(dirPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }

            // 最终文件
            File realFile = new File(dirPath + File.separator + file.getOriginalFilename());
            // 保存文件
            FileUtils.copyInputStreamToFile(file.getInputStream(), realFile);

            // 下面返回的json格式是editor.md所限制的，规范输出就OK，我用的map组装了一下
            map.put("success", 1);
            map.put("message", "上传成功");
            String url = "/upload/"+file.getOriginalFilename();
            map.put("url", url);//这个url会被页面拼接，
        } catch (Exception e) {
            map.put("success", 0);
            map.put("message", "上传失败");
            map.put("url", "");
            e.printStackTrace();
        }
        System.out.println(map.get("messgae"));
        return map;
    }
}
